<?php

namespace App\Admin\Controllers;

use App\Models\Order;
use App\Models\ShopRoomTable;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Box;
use App\Admin\Extensions\ExcelExpoter;

class ShopOrderController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->grid());
        });
    }



    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Order::class, function (Grid $grid) {
            $excel = new ExcelExpoter();
            $excel->setAttr(
                ['id', '店铺名称','订单编号','订单类型(0外卖,1预定 ,2排队 ,3扫码 ,4直接付款 ,5充值,6优惠卡)','订单状态(2支付成功,3进行中,4已收货待评价,5已收货已评价,-1发起退单,-2同意退单,-3订单关闭)','买家（为空是未登录用户）','订单价格','实际价格','支付方式（0余额，1微信，2支付宝）','下单时间','更新时间'],
                ['id', 'shop.shop_name','order_number','order_type','order_status','users.mobile','order_price','order_amount','pay_way','created_at','updated_at'],'订单'
            );
            $grid->exporter($excel);
            $grid->model()->orderBy('id', 'desc');
            $grid->disableCreateButton();
            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                // 在这里添加字段过滤器
                $filter->like('Shop.shop_name', '商铺名称');
                $filter->like('users.mobile', '买家');
                $filter->like('order_number', '订单编号');
                $filter->in('order_type','订单类型')->checkbox([
                    0    => '外卖',
                    1    => '预定',
                    2    => '排队',
                    3    => '扫码',
                    4    => '直接付款',
                    5    => '充值',
                ]);
                $filter->in('order_status','订单状态')->checkbox([
                    2    => '支付成功',
                    3    => '进行中',
                    4    => '已完成',
                    5    => '已完成',
                    -1    => '退单待同意',
                    // -2    => '同意退单',
                    -3    => '退单完成',
                ]);
                $filter->in('pay_way','支付方式')->checkbox([
                    0    => '余额',
                    1    => '微信',
                    2    => '支付宝',
                ]);
                $filter->between('created_at', '时间筛选')->datetime();
            });
            $grid->id('ID')->sortable();
            $grid->model()->where('order_status','<>',0);
            $grid->model()->where('order_status','<>',1);
            $grid->column('Shop.shop_name','店铺名称');
            $grid->column('order_number','订单编号');
            $grid->order_type('订单类型')->display(function ($order_type){
                switch ($order_type){
                    case '1':
                        return '预定';
                        break;
                    case '2':
                        return '排队';
                        break;
                    case '3':
                        return '扫码';
                        break;
                    case '4':
                        return '直接付款';
                        break;
                    case '5':
                        return '充值';
                        break;
                    case '0':
                        return '外卖';
                        break;
                    default:
                        return 'yes';
                        break;
                }
            });
            $grid->order_status('订单状态')->display(function ($order_status){
                switch ($order_status){
                    case '2':
                        return "<span style='color:#00c0ef'>支付成功</span>";
                        break;
                    case '3':
                        return "<span style='color:#0044cc'>进行中</span>";
                        break;
                    case '4':
                        return "<span style='color:#01B488'>已完成</span>";
                        break;
                    case '5':
                        return "<span style='color:#01B488'>已完成</span>";
                        break;
                    case '-1':
                        return "<span style='color:#c0a16b'>退单待同意</span>";
                        break;
                    case '-2':
                        return "<span style='color:#c0a16b'>同意退单</span>";
                        break;
                    case '-3':
                        return '订单关闭';
                        break;
                    default:
                        return '无效单';
                        break;
                }
            });
            $grid->column('users.mobile','买家')->display(function ($mobile){
                if($mobile == '') {
                    return '游客';
                }else{
                    return $mobile;
                }
            });
            $grid->column('order_price','订单价格');
            $grid->column('order_amount','实际价格')->display(function ($amount){
                return isset($amount) ? $amount:'无';
            });
            $grid->column('pay_way','支付方式')->display(function ($order_status){
                switch ($order_status) {
                    case '0':
                        return "<span class='badge bg-yellow-gradient'>余额</span>";
                        break;
                    case '1':
                        return "<span class='badge bg-green-gradient'>微信</span>";
                        break;
                    case '2':
                        return "<span class='badge bg-blue-gradient'>支付宝</span>";
                        break;
                    default:
                        return "<span class='badge bg-yellow-gradient'>余额</span>";
                        break;
                }
            });
            $grid->column('created_at','下单时间')->sortable();
            $grid->column('updated_at','更新时间')->sortable();
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $order_id = $actions->getKey();
                //$actions->append('<a href="/admin/shop/orders/detail?order_id='.$order_id.'"><i class="fa fa-eye">订单详情</i></a>');
                $actions->append('&nbsp;&nbsp;<a href="/admin/order/detail?order_id='.$order_id.'"><i class="fa fa-eye">订单详情</i></a>');
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Order::class, function (Form $form) {
            // 0外卖 1预定 2排队 3扫码 4直接付款 5充值
            $form->display('id', 'ID');
            $form->hasMany("orderdetail", "菜单",function ($form) {
                $form->text('dishes_name', '菜名');
                $form->text('goods_number', '数量');
                $form->text('price', '原价');
                $form->text('sell_price', '实际售价');
                $form->text('amount', '总价');
            });

            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
            // $form->disableSubmit();
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $order = $this->order($id);
            $content->header('header');
            $content->description('description');

            $content->body($this->form($order)->edit($id));
        });
    }


    public function editdetail()
    {
        return Admin::content(function (Content $content){
            //dd($this->order($id));
            $content->header('订单详情');
            $content->description('');

            $content->body($this->editfinanceform()->edit(request('order_id')));
        });
    }


    protected function editfinanceform()
    {
        return Admin::form(Order::class, function (Form $form) {
//            $form->setAction('/admin/users/'.request('user_id'));
            $form->display('id', 'ID');
            $form->text('created_at', 'Created At');
            $form->text('created_at', 'Created At');
            $form->text('created_at', 'Created At');
            $form->text('created_at', 'Created At');
            $form->text('created_at', 'Created At');
            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
//            $form->text('updated_at', '更新时间');
        });
    }

    public function order($id)
    {
        $order = Order::where('id',$id)->first();
        return $order;
    }
    //订单详情
    public function one(Request $request)
    {
        try{
            return Admin::content(function (Content $content) {

                $content->header('订单详情');
                $content->description('deatil');

                $content->body($this->griddetail());
            });
        }catch (\Exception $e){
            return redirect('/shop/printer');
        }
    }
    //订单详情
    protected function griddetail()
    {
        return Admin::grid(Order::class, function (Grid $grid) {
            $grid->disableActions();
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
            });
            $grid->disableFilter();//禁用查询
            $grid->disableCreateButton();//禁用新增
            $grid->disableExport();//禁用导出
            $grid->disablePagination();//禁用分页条
            $grid->model()->where('id',\request('order_id'));
            $grid->id('ID');
            //订单类型
            $order_type = $this->order(\request('order_id'))->order_type;
            //菜式详情
            $order = Order::with('OrderDetail')
                ->with('OrderAddress')
                ->with('orderReserve')
                ->where('id',\request('order_id'))
                ->first();

            if(count($order->orderdetail)>0) {
                $table = '';
                foreach ($order->orderdetail as $key => $value) {
                    $table .= "<tr>
                                    <th>$value->dishes_name</th>
                                    <th>$value->goods_number</th>
                                    <th>$value->price</th>
                                    <th>$value->sell_price</th>
                                    <th>$value->amount</th>
                               </tr>";
                }
                $value = "<thead>
                                <tr>
                                <th>菜名</th>
                                <th>数量</th>
                                <th>原价</th>
                                <th>实际售价</th>
                                <th>总价</th>
                                </tr>
                          </thead>
                                <tbody>
                                      $table
                                </tbody>";
                $box = new Box('菜式详情', "<table class='table'>$value</table>");

                $box->style('info');

                $box->solid();

                echo $box;
            }

            $grid->order_type('订单类型')->display(function ($order_type){
                switch ($order_type){
                    case '1':
                        return '预定';
                        break;
                    case '2':
                        return '排队';
                        break;
                    case '3':
                        return '扫码';
                        break;
                    case '4':
                        return '直接付款';
                        break;
                    case '5':
                        return '充值';
                        break;
                    case '0':
                        return '外卖';
                        break;
                    default:
                        return 'yes';
                        break;
                }
            });
            $grid->order_status('订单状态')->display(function ($order_status){
                switch ($order_status){
                    case '2':
                        return '支付成功';
                        break;
                    case '3':
                        return '进行中';
                        break;
                    case '4':
                        return '已完成';
                        break;
                    case '-1':
                        return '退单待同意';
                        break;
                    case '-2':
                        return '同意退单';
                        break;
                    case '-3':
                        return '订单关闭';
                        break;
                    default:
                        return '无效单';
                        break;
                }
            });
            //外卖
            if($order_type == 0) {
                $grid->OrderAddress()->address('收货地址')->display(function ($address) use ($order) {
                    if ($order->OrderAddress) {
                        return $address . $order->OrderAddress->address_detail;
                    }
                });
            }
            //预定
            if($order_type == 1) {
                $grid->orderReserve()->desk_room('房桌')->display(function ($desk_room) use ($order) {
                    $RD = explode('|',$desk_room);
                    if(empty($RD[0])){
                        $roomDesk = null;
                    }else {
                        foreach ($RD as $key => $value) {
                            $roomDesk[] = ShopRoomTable::RoomTableFirst($value);
                        }
                    }
                    if($roomDesk) {
                        $data = '';
                        for ($i = 0; $i < count($roomDesk); $i++) {
                            //dd($roomDesk[1]->name);
                            $data = $data . '—' . $roomDesk[$i]->name;
                        }
                        $data = ltrim($data, "—");
                        return $data;
                    }
                });
                $grid->column('orderReserve.name','预订人姓名');
                $grid->column('orderReserve.arrive_time','到达时间');
                $grid->column('order_amount','订单总价');
            }
            $grid->column('created_at','下单时间');
            $grid->column('updated_at','更新时间');

        });
    }

    public function shopOrder()
    {
        return Admin::content(function (Content $content) {

            $content->header('某商家的所有订单');
            $content->description('');
            $content->breadcrumb(
                ['text' => '查看商家', 'url' => '/shops'],
                ['text' => '']
            );
            $content->body($this->gridShop());
        });
    }
    protected function gridShop()
    {
        return Admin::grid(Order::class, function (Grid $grid) {
            $grid->tools(function ($tools) {
                $tools->batch(function ($actions) {
                    $actions->disableDelete();

                });
            });
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
            });
            $grid->disableFilter();//禁用查询
            $grid->disableCreateButton();//禁用新增
            $grid->disablePagination();//禁用分页条

            $grid->model()->where('shop_id',request('shop_id'));
            $grid->id('ID')->sortable();
            $grid->column('shop_id','商家id');
            $grid->column('order_number','订单编号');
            $grid->order_type('订单类型')->display(function ($type){
                switch ($type){
                    case '1':
                        return '预定';
                        break;
                    case '2':
                        return '外卖扫码';
                        break;
                    case '3':
                        return '预定扫码';
                        break;
                    case '4':
                        return '直接付款';
                        break;
                    case '5':
                        return '充值';
                        break;
                    case '0':
                        return '外卖';
                        break;
                    default:
                        return 'yes';
                        break;
                }
            });
            $grid->order_status('订单状态')->display(function ($order_status){
                switch ($order_status){
                    case '0':
                        return '刚创建';
                        break;
                    case '1':
                        return '待配送';
                        break;
                    case '2':
                        return '待配送';
                        break;
                    case '3':
                        return '待收货';
                        break;
                    case '4':
                        return '已完成';
                        break;
                    case '-1':
                        return '退单待同意';
                        break;
                    case '-2':
                        return '同意退单';
                        break;
                    case '-3':
                        return '订单关闭';
                        break;
                    default:
                        return '无效单';
                        break;
                }
            });
            $grid->column('order_price','订单总额');
            $grid->column('order_amount','订单欠额')->display(function ($amount){
                return isset($amount) ? $amount:'无';
            });
            $grid->column('created_at','创建时间');
            $grid->column('updated_at','更新时间');
            $grid->actions(function ($actions) {
                $order_id = $actions->getKey();
                //$actions->append('<a href="/admin/shop/orders/detail?order_id='.$order_id.'"><i class="fa fa-eye">订单详情</i></a>');
                $actions->append('&nbsp;&nbsp;<a href="/admin/order/detail?order_id='.$order_id.'"><i class="fa fa-eye">订单详情</i></a>');
            });
        });
    }
}
